package com.fili.core;

import com.fili.core.FetchThreadListener;

import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by Claudiu-Florin FILIMON
 * Date: Oct 18, 2006
 * Time: 4:55:13 PM
 * Revision: 0
 */
public class FetchThread extends Thread
{
    private FetchThreadListener listener;
    private String command;

    public FetchThread(String command, FetchThreadListener listener)
    {
        this.command = command;
        this.listener = listener;
        start();
    }

    public void run()
    {
        try
        {
            Process proc = Runtime.getRuntime().exec(command);
            StreamBufferer bufInput = new StreamBufferer(proc.getInputStream());
            StreamBufferer bufError = new StreamBufferer(proc.getErrorStream());

            proc.waitFor();

            while (!bufInput.isFinished())
                Thread.sleep(100);
            while (!bufError.isFinished())
                Thread.sleep(100);


            listener.fetchThreadFinished(bufInput.getBuffer().toString(), bufError.getBuffer().toString(), proc.exitValue());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}